home *** CD-ROM | disk | FTP | other *** search
- Path: news.halcyon.com!usenet
- From: normanb@halcyon.com (Norm Bryar)
- Newsgroups: comp.lang.c++
- Subject: Re: Newbie question re: struct pointers & member access
- Date: Fri, 08 Mar 1996 16:07:30 GMT
- Organization: Northwest Nexus Inc.
- Message-ID: <4hplup$f3@news.halcyon.com>
- References: <4hn0v2$7q5@aahz.magic.mb.ca>
- NNTP-Posting-Host: blv-pm3-ip14.halcyon.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- jranta@astral.magic.ca (jranta) wrote:
-
- >Hi!
- >I am attempting to write a simple program to prepare myself for a C++ course
- >at school. The program is to request from the user how many cars to catalog
- >and to then record this many cars. I'm using the "new" operator to allocate
- >the proper number of structures; there doesn't seem to be a problem with input
- >but when I attempt to ouput using the pointer, all I get is NULL for each
- >record.
-
- >Here is the code so far:
-
- >#include<iostream.h>
- >#include<conio.h>
-
- >const int ArSize = 30;
- >void enter(int t);
-
- >struct car
- > {
- > char make[ArSize];
- > int year;
- > };
- >int main(void)
- >{
- > int total;
- > clrscr();
- > cout<<"How many cars do you wish to catalog?";
- > cin>>total;
- > enter(total);
-
- >return 0;
- >}
- >void enter(int t)
- >{
- > car *ptr = new car[t];
- > for(int a=0;a<t;a++,ptr++)
- > {
- > cin.get(); //to clear input queue(alt. between strings & numbers).
- > cout<<"Car #"<<a+1;
- > cout<<"\nPlease enter make: ";
- > cin.getline(ptr->make,ArSize);
- > cout<<"\nEnter year: ";
- > cin>>ptr->year;
- > }
- >return;
- >}
-
- >I attempted to use another "for" loop to display output, but I think that I'm
- >not setting the pointer properly at the first record. This is where my
- >confusion lies: how do I set the pointer at the beginning and then increment
- >it? My output was all NULL, as mentioned above, so I guess that I was
- >displaying from the last pointer position and on, resulting in garbage.
-
- >Any help/hints would be appreciated (I know this concept is *very* important
- >for OOP, which is what my course is.).
-
- >If preferred and/or convenient, e-mail me at:
-
- >jranta@astral.magic.ca
-
- >Thanks a lot in advance,
- >Jouni
-
- The enter() function doesn't seem to be doing any output at all, nor
- returning the allocated pointer of cars, but I suspect the problem is
- you were trying to re-use ptr?
-
- Perhaps you need a second car *, one to march through inputting, the
- other for outputting.
-
- car * pCars,
- pACar;
-
- pACar = pCars = new car[ N ];
- if( NULL == pCars )
- // oopse, out of memory
- for( a=0; a<N; a++, pACar++ )
- {
- // input into pACar
- }
-
- pACar = pCars; // rest to beginning
- for( a=0; a<N; a++, pACar++)
- {
- // output...
- }
-
- Does this help?
-
- --Norm
-
-